package com.example.myjavafx.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.JsonObject;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;

import java.io.ByteArrayInputStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Base64;
import javafx.scene.control.TextInputDialog;
import javafx.scene.image.WritableImage;
import javafx.scene.image.PixelReader;
import javafx.scene.image.PixelWriter;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.StackPane;
import javafx.scene.shape.Rectangle;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Optional;

// ImageController.java
public class ImageController {
    @FXML
    public ImageView preview;
    @FXML
    public StackPane imageContainer;
    @FXML
    public Rectangle cropRect;
    @FXML
    private ImageView imageView;

    private final HttpClient client = HttpClient.newHttpClient();
    private Image currentImage;  // 保存当前图像

    @FXML
    private void cropImage() {
//        if (currentImage == null) {
//            showError("请先获取图像");
//            return;
//        }

        // 弹出对话框让用户输入剪切参数
        TextInputDialog dialog = new TextInputDialog("500,500,1500,1000");
        dialog.setTitle("图像剪切");
        dialog.setHeaderText("输入剪切区域坐标 (x1,y1,x2,y2)");
        dialog.setContentText("请输入剪切区域坐标（格式：起始x,起始y,结束x,结束y）:");

        Optional<String> result = dialog.showAndWait();
        result.ifPresent(roiStr -> {
            try {
                // 解析ROI坐标
                String[] coords = roiStr.split(",");
                if (coords.length != 4) {
                    showError("坐标格式错误，请输入四个数字");
                    return;
                }

                int x1 = Integer.parseInt(coords[0]);
                int y1 = Integer.parseInt(coords[1]);
                int x2 = Integer.parseInt(coords[2]);
                int y2 = Integer.parseInt(coords[3]);

                // 验证坐标合法性
                if (x1 < 0 || y1 < 0 || x2 > currentImage.getWidth() || y2 > currentImage.getHeight() || x1 >= x2 || y1 >= y2) {
                    showError("无效的剪切区域坐标");
                    return;
                }

                // 计算剪切区域宽高
                int width = x2 - x1;
                int height = y2 - y1;

                // 创建剪切图像
                WritableImage croppedImage = new WritableImage(width, height);
                PixelReader pixelReader = currentImage.getPixelReader();
                PixelWriter pixelWriter = croppedImage.getPixelWriter();

                // 复制像素
                for (int readY = y1; readY < y2; readY++) {
                    for (int readX = x1; readX < x2; readX++) {
                        int argb = pixelReader.getArgb(readX, readY);
                        pixelWriter.setArgb(readX - x1, readY - y1, argb);
                    }
                }

                // 发送剪切后的图像到后端
                sendCroppedImageToBackend(croppedImage, x1, y1, width, height);

                // 显示剪切后的图像
                imageView.setImage(croppedImage);

            } catch (NumberFormatException e) {
                showError("请输入有效的数字坐标");
            } catch (Exception e) {
                showError("剪切图像失败: " + e.getMessage());
            }
        });
    }

    private void sendCroppedImageToBackend(Image croppedImage, int x, int y, int width, int height) {
        Task<Void> task = new Task<>() {
            @Override
            protected Void call() throws Exception {
                // 将图像转换为Base64
                String base64Image = imageToBase64(croppedImage);

                // 构建JSON请求体
                JsonObject requestBody = new JsonObject();
                requestBody.addProperty("image", base64Image);

                // 构建ROI对象
                JsonObject roiObject = new JsonObject();
                roiObject.addProperty("x", x);
                roiObject.addProperty("y", y);
                roiObject.addProperty("width", width);
                roiObject.addProperty("height", height);

                requestBody.addProperty("roi", roiObject.toString());

                HttpRequest request = HttpRequest.newBuilder()
                    .header("Content-Type", "application/json")
                    .uri(URI.create("http://192.168.0.173:12345/api/crop"))  // 假设后端有新的裁剪API
                    .POST(HttpRequest.BodyPublishers.ofString(requestBody.toString()))
                    .build();

                HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
                System.out.println("裁剪响应: " + response.body());

                return null;
            }
        };

        task.setOnFailed(e -> showError("发送裁剪请求失败: " + task.getException().getMessage()));
        new Thread(task).start();
    }

    private String imageToBase64(Image image) throws Exception {
        // 将JavaFX Image转换为Base64编码
        BufferedImage bufferedImage = SwingFXUtils.fromFXImage(image, null);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, "png", baos);
        byte[] bytes = baos.toByteArray();
        return Base64.getEncoder().encodeToString(bytes);
    }


    @FXML
    private void fetchImage() {
        Task<Image> task = new Task<>() {
            @Override
            protected Image call() throws Exception {
//                HttpRequest request = HttpRequest.newBuilder()
//                        .uri(URI.create("http://localhost:5000/capture"))
//                        .build();
                // 创建请求体
//                String requestBody = "{\"type\":\"image\"}";
                JsonObject requestBody = new JsonObject();
//                requestBody.addProperty("url", imageView.getImage().getUrl());
                requestBody.addProperty("mode", "invoking");
                requestBody.addProperty("class_name", "MVCameraControl");
                requestBody.addProperty("function_name", "capture");
                requestBody.addProperty("timeout", 200);

                HttpRequest request = HttpRequest.newBuilder()
                        .header("Content-Type", "application/json")
                        .uri(URI.create("http://192.168.0.173:12345/api/control"))
                        .POST(HttpRequest.BodyPublishers.ofString(requestBody.toString()))
                        .build();

                HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
                String json = response.body();

                // 解析JSON获取Base64图像数据
                ObjectMapper mapper = new ObjectMapper();
                JsonNode node = mapper.readTree(json);
                String base64Image = node.get("data").asText();

                // 解码Base64为字节数组
                byte[] imageData = Base64.getDecoder().decode(base64Image);
                return new Image(new ByteArrayInputStream(imageData));
            }
        };

        task.setOnSucceeded(e -> imageView.setImage(task.getValue()));
        task.setOnFailed(e -> showError("加载失败: " + task.getException().getMessage()));

        new Thread(task).start();
    }


    private void showError(String message) {
        Platform.runLater(() -> {
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setContentText(message);
            alert.show();
        });
    }

    public void handleMousePressed(MouseEvent mouseEvent) {
    }

    public void handleMouseDragged(MouseEvent mouseEvent) {
    }

    public void handleCrop(ActionEvent actionEvent) {
        // 裁剪逻辑
        // ...
    }
}